export const setToken = (token: string) => {
  uni.setStorageSync('token', token)
}

export const getToken = () => {
  return uni.getStorageSync('token') || ''
}

export function create_storage_get_set(key: string) {
  const defaultValueMapper: Record<string, string | Record<string, any>> = {
    token: '',
    history: [],
  }
  return {
    get: () => uni.getStorageSync(key) || (key in defaultValueMapper ? defaultValueMapper[key] : {}),
    set: (value: Record<string, any>) => uni.setStorageSync(key, value),
    remove: () => uni.removeStorageSync(key),
  }
}

interface CityInfoType {
  city: string
  cityId: number
  district: string
  districtId: number
  province: string
  provinceId: number
}

type GetReturnType<T extends string> =
  T extends 'token' ? string :
  T extends 'user' ? { id: number, name: string, [key: string]: any } :
  T extends 'location' ? { latitude: number, longitude: number, [key: string]: any } & Partial<CityInfoType> :
  T extends 'history' ? string[] :
  Record<string, any>

// type FirstOf<T> = T extends infer U ? U : never; // infer U 用来推断类型
type PropertyAccessor<T extends string> = {
  [K in `get${Capitalize<T>}`]: <P extends T>() => GetReturnType<P>
} & {
  [K in `set${Capitalize<T>}`]: (value: any) => void
} & {
  [K in `remove${Capitalize<T>}`]: () => void
}

type KnownStorageKeys = 'token' | 'user' | 'location' | 'normal' | 'history' | 'servecate'
type StorageKeys = KnownStorageKeys

const targetSource = {}

export const storageHelper = new Proxy(targetSource as PropertyAccessor<StorageKeys>, {
  get(_target, key) {
    const keyStr = String(key.toString().replace(/(get|set|remove)/g, ''))
    const keyType = key.toString().replace(keyStr, '') as 'get' | 'set' | 'remove'
    return create_storage_get_set(keyStr.toLowerCase())[keyType]
  },
})
